package com.example.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.Constants;
import com.example.common.PageResult;
import com.example.common.enums.ErrorCodeEnum;
import com.example.common.enums.PetShopStatusEnum;
import com.example.common.enums.RoleEnum;
import com.example.exception.CustomException;
import com.example.mapper.GoodsOrdersMapper;
import com.example.mapper.PetOrdersMapper;
import com.example.mapper.PetShopMapper;
import com.example.pojo.entity.*;
import com.example.pojo.vo.PetShopHotVo;
import com.example.pojo.vo.PetShopQueryVo;
import com.example.utils.AccountUtils;
import com.example.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 宠物店 service 层实现类
 */
@Service
public class PetShopServiceImpl extends ServiceImpl<PetShopMapper, PetShop> implements PetShopService {

    @Resource
    @Lazy
    private PetService petService;

    @Resource
    private PetOrdersMapper petOrdersMapper;

    @Resource
    private GoodsOrdersMapper goodsOrdersMapper;

    /**
     * 创建一个宠物店账号
     *
     * @param petShop 宠物店
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(PetShop petShop) {
        // 1.判空
        if (petShop == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        // 2.用户名不能为空
        if (StrUtil.isBlank(petShop.getUsername())) {
            throw new CustomException(ErrorCodeEnum.USER_NAME_IS_NOT_NULL);
        }
        // 3.没有昵称默认用账号名
        if (StrUtil.isBlank(petShop.getName())) {
            petShop.setName(petShop.getUsername());
        }
        // 4.没有密码默认用默认密码
        if (StrUtil.isBlank(petShop.getPassword())) {
            petShop.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        // 5.角色是宠物店
        petShop.setRole(RoleEnum.PETSHOP.name());
        // 6.判断此用户名是否存在
        PetShop dbPetShop = this.lambdaQuery()
                .eq(PetShop::getUsername, petShop.getUsername())
                .one();
        if (dbPetShop != null) {
            throw new CustomException(ErrorCodeEnum.USER_EXIST_ERROR);
        }
        // 7.初始状态是待提交
        petShop.setStatus(PetShopStatusEnum.INIT.getName());
        // 8.创建账号
        this.save(petShop);
    }

    /**
     * 分页查询宠物店
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     * @param petShop  条件
     * @return 分页结果
     */
    @Override
    public PageResult<PetShopQueryVo> pageQuery(Integer pageNum, Integer pageSize, PetShop petShop) {
        // 1.校验参数
        if (pageNum == null || pageNum < 1) {
            throw new CustomException(ErrorCodeEnum.PAGE_QUERY_NUM);
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            throw new CustomException(ErrorCodeEnum.PAGE_QUERY_SIZE);
        }

        // 2.创建 MybatisPlus 分页对象
        IPage<PetShop> pageObject = new Page<>(pageNum, pageSize);

        // 3.分页查询宠物店
        pageObject = this.getBaseMapper().pageQuery(pageObject, petShop);

        // 4.获取宠物店结果集合
        List<PetShop> petShopList = pageObject.getRecords();
        List<PetShopQueryVo> petShopVoList = new ArrayList<>();

        // 5.查询每个宠物店的所有宠物
        if (CollectionUtil.isNotEmpty(petShopList)) {
            for (PetShop shop : petShopList) {
                // 5.1 根据宠物店 id 查询宠物
                List<Pet> petList = this.petService.lambdaQuery()
                        .eq(Pet::getShopId, shop.getId())
                        .list();
                // 5.2 构建 vo
                PetShopQueryVo vo = BeanUtil.copyProperties(shop, PetShopQueryVo.class);
                vo.setPetList(petList);
                petShopVoList.add(vo);
            }
        }

        // 5.构建分页结果并返回
        return new PageResult<>(
                pageObject.getTotal(),
                petShopVoList
        );
    }

    /**
     * 根据宠物店id，查询宠物店
     *
     * @param id 宠物店id
     * @return 宠物店
     */
    @Override
    public PetShop queryById(Integer id) {
        // 1.校验参数
        if (id == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        // 2.根据宠物店id，查询宠物店
        PetShop petShop = this.lambdaQuery()
                .eq(PetShop::getId, id)
                .one();
        // 3.隐藏密码
        petShop.setPassword(null);
        // 4.返回宠物店
        return petShop;
    }

    /**
     * 根据条件查询全部宠物店
     *
     * @param petShop 条件
     * @return 宠物店
     */
    @Override
    public List<PetShop> queryAll(PetShop petShop) {
        // 1.根据条件查询全部宠物店
        List<PetShop> petShopList = this.getBaseMapper().query(petShop);
        // 2.隐藏密码
        for (PetShop shop : petShopList) {
            shop.setPassword(null);
        }
        return petShopList;
    }

    /**
     * 修改宠物店
     *
     * @param petShop 宠物店
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PetShop petShop) {
        // 1.校验参数
        if (petShop == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (petShop.getId() == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (StrUtil.isBlank(petShop.getName())) {
            throw new CustomException(ErrorCodeEnum.PET_SHOP_NAME_ERROR);
        }

        // 2.根据宠物店id，修改宠物店
        this.updateById(petShop);
    }

    /**
     * 登录
     *
     * @param account 账号
     * @return 账号
     */
    @Override
    public PetShop login(Account account) {
        // 1.校验账号是否存在
        PetShop dbPetShop = this.lambdaQuery()
                .eq(PetShop::getUsername, account.getUsername())
                .one();
        if (dbPetShop == null) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_EXIST_ERROR);
        }
        // 2.校验密码
        if (!dbPetShop.getPassword().equals(account.getPassword())) {
            throw new CustomException(ErrorCodeEnum.USER_PASSWORD_ERROR);
        }

        // 3.创建 jwt token
        // token 内容 = 账号id-角色，如 23-ADMIN
        // 密钥 = 账号密码
        String token = TokenUtils.createToken(dbPetShop.getId() + "-" + dbPetShop.getRole(), dbPetShop.getPassword());
        // 4.封装账号
        // 4.1 token存入对象
        dbPetShop.setToken(token);
        // 4.2 不返回密码
        dbPetShop.setPassword(null);
        // 5.返回账号
        return dbPetShop;
    }

    /**
     * 修改账号密码
     *
     * @param account 账号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Account account) {
        // 1.根据用户名称校验账号是否存在
        PetShop dbPetShop = this.lambdaQuery()
                .eq(PetShop::getUsername, account.getUsername())
                .one();
        if (dbPetShop == null) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_EXIST_ERROR);
        }
        // 2.根据用户输入的原密码校验与数据库的密码是否一致
        if (!dbPetShop.getPassword().equals(account.getPassword())) {
            throw new CustomException(ErrorCodeEnum.PARAM_OLD_PASSWORD_ERROR);
        }
        // 3.将用户输入的新密码存入数据库
        this.lambdaUpdate()
                .eq(PetShop::getUsername, account.getUsername())
                .set(PetShop::getPassword, account.getNewPassword())
                .update();
    }

    /**
     * 宠物店提交认证材料
     *
     * @param petShop 认证材料
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitIdentify(PetShop petShop) {
        // 1.校验参数
        if (petShop == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (petShop.getId() == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (StrUtil.isBlank(petShop.getPracticeLicense())) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (StrUtil.isBlank(petShop.getPrincipalName())) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (StrUtil.isBlank(petShop.getPrincipalNo())) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }

        // 2.获取当前登录的账户，校验当前用户是否是宠物店
        Account currentLoginAccount = AccountUtils.getCurrentLoginAccount();
        if (currentLoginAccount == null) {
            throw new CustomException(ErrorCodeEnum.GET_CUR_USER_ERROR);
        }
        if (!RoleEnum.PETSHOP.name().equals(currentLoginAccount.getRole())) {
            throw new CustomException(ErrorCodeEnum.ONLY_PET_SHOP_SUBMIT);
        }

        // 3.只有认证状态为"待提交"或“审核拒绝”才可以提交
        PetShop dbPetShop = this.lambdaQuery()
                .eq(PetShop::getId, petShop.getId())
                .one();
        if (dbPetShop == null) {
            throw new CustomException(ErrorCodeEnum.PET_SHOP_NOT_EXIST);
        }
        if (!PetShopStatusEnum.INIT.getName().equals(dbPetShop.getStatus()) && !PetShopStatusEnum.FAIL.getName().equals(dbPetShop.getStatus())) {
            throw new CustomException(ErrorCodeEnum.ONLY_INIT_STATUS_SUBMIT);
        }

        // 4.修改宠物店认证状态为"待审核"
        this.lambdaUpdate()
                .eq(PetShop::getId, petShop.getId())
                .set(PetShop::getPracticeLicense, petShop.getPracticeLicense())
                .set(PetShop::getPrincipalName, petShop.getPrincipalName())
                .set(PetShop::getPrincipalNo, petShop.getPrincipalNo())
                .set(PetShop::getStatus, PetShopStatusEnum.SUBMIT.getName())
                .update();
    }

    /**
     * 管理员审核认证材料
     *
     * @param petShop 认证材料
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditIdentify(PetShop petShop) {
        // 1.校验参数
        if (petShop == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (petShop.getId() == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (StrUtil.isBlank(petShop.getStatus())) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }

        // 2.获取当前登录的账户，校验当前用户是否是管理员
        Account currentLoginAccount = AccountUtils.getCurrentLoginAccount();
        if (currentLoginAccount == null) {
            throw new CustomException(ErrorCodeEnum.GET_CUR_USER_ERROR);
        }
        if (!RoleEnum.ADMIN.name().equals(currentLoginAccount.getRole())) {
            throw new CustomException(ErrorCodeEnum.ONLY_ADMIN_AUDIT);
        }

        // 3.只有认证状态为"待审核"才可以提交
        PetShop dbPetShop = this.lambdaQuery()
                .eq(PetShop::getId, petShop.getId())
                .one();
        if (dbPetShop == null) {
            throw new CustomException(ErrorCodeEnum.PET_SHOP_NOT_EXIST);
        }
        if (!PetShopStatusEnum.SUBMIT.getName().equals(dbPetShop.getStatus())) {
            throw new CustomException(ErrorCodeEnum.ONLY_SUBMIT_STATUS_AUDIT);
        }

        // 4.修改宠物店认证状态
        this.lambdaUpdate()
                .eq(PetShop::getId, petShop.getId())
                .set(PetShop::getStatus, petShop.getStatus())
                .update();
    }

    /**
     * 统计所有宠物店的销售额，并从大到小排序
     *
     * @return 宠物店 vo 列表
     */
    @Override
    public List<PetShopHotVo> countAllPetShopSale() {
        // 1.查询所有认证状态为"审核通过"的宠物店id列表
        List<PetShop> petShopList = this.lambdaQuery()
                .eq(PetShop::getStatus, PetShopStatusEnum.SUCCESS.getName())
                .list();

        List<PetShopHotVo> voList = BeanUtil.copyToList(petShopList, PetShopHotVo.class);

        // 2.遍历宠物店，计算每个宠物店的销售额
        for (PetShopHotVo vo : voList) {
            // 从宠物订单计算销售额
            BigDecimal petAllAmount = this.petOrdersMapper.countAmountByShopId(vo.getId());
            // 从宠物用品订单计算销售额
            BigDecimal goodsAllAmount = this.goodsOrdersMapper.countAmountByShopId(vo.getId());
            // 宠物店的销售额 = 宠物销售额 + 宠物用品销售额
            vo.setSales(petAllAmount.add(goodsAllAmount));
        }

        // 3.按销售额从大到小排序
        return voList.stream().sorted(Comparator.comparing(PetShopHotVo::getSales, Comparator.reverseOrder())).toList();
    }
}
